<template>
  <div class="proxy-setting">
    <div class="item title">
      <div class="btns">
        <a-button type="primary" @click="addAgentHandle()">
          添加代理人
        </a-button>
        <a-button type="primary" @click="refresh()">
          刷新
        </a-button>
      </div>
    </div>
    <div class="item table">
      <a-table
        :loading="table.loading"
        :columns="table.columns"
        :data-source="table.dataSource"
        :show-header="true"
        :pagination="false"
        :row-key="record => record.id"
        :rowClassName="setRowClassName"
        :scroll="{ y: 330 }">
        <template slot="action" slot-scope="text, record, index">
          <span class="display-line cursor-pointer" title="编辑">
            <i type="small" size="small" class="icon iconfont icon-edit" @click="handleEdit(record)" style="margin-right:4px"/>
          </span>
          <span class="display-line cursor-pointer" title="删除">
            <a-popconfirm
              title="是否确认删除？"
              @confirm="() => handleDelete(record)"
            >
              <a href="javascript:;" class="icon iconfont icon-delete"/>
            </a-popconfirm>
          </span>
        </template>
      </a-table>
    </div>

    <a-modal
      title="添加代理人"
      :visible="proxyVisible"
      @ok="handleOkEditProxy('proxyInfo')"
      @cancel="handleCancelEdit('proxyInfo')"
      width="30%"
      centered>
      <div class="w-full">
        <a-form-model ref="proxyInfo" :model="proxyInfo" :rules="rules" v-bind="layout">
          <a-form-model-item has-feedback label="代理人" prop="agentName">
            <a-tree-select
              v-model="proxyInfo.agentId"
              :tree-data="treeData"
              :replaceFields="{ value: 'id', title: 'name', scopedSlots: { title: 'custom' } }"
              show-search
              style="width: 100%"
              :dropdown-style="{ maxHeight: '300px', overflow: 'auto' }"
              placeholder="请选择代理人"
              allow-clear
              tree-default-expand-all
              @select="onSelect"
            >
            </a-tree-select>
          </a-form-model-item>
          <a-form-model-item has-feedback label="开始时间" prop="beginTime">
            <a-date-picker
              v-model="proxyInfo.beginTime"
              show-time
              type="date"
              format="YYYY-MM-DD"
              :disabled-date="disabledBeginTime"
              @openChange="handleBeginOpenChange"
              placeholder="请选择开始时间"
              style="width: 100%;"
            />
          </a-form-model-item>
          <a-form-model-item has-feedback label="结束时间" prop="endTime">
            <a-date-picker
              v-model="proxyInfo.endTime"
              show-time
              type="date"
              format="YYYY-MM-DD"
              :disabled-date="disabledEndTime"
              @openChange="handleEndOpenChange"
              :open="endOpen"
              placeholder="请选择结束时间"
              style="width: 100%;"
            />
          </a-form-model-item>
        </a-form-model>
      </div>
    </a-modal>
  </div>
</template>

<script>
  import orupService from '@/api/orupService'
  import { getColumns } from '@/api/tableColumns'
  export default {
    name: 'ProxySetting',
    props: {},
    data () {
      const validateBeginTime = (rule, value, callback) => {
        if (!value) {
          callback(new Error('请选择开始时间'))
        }
        callback()
      }
      const validateEndTime = (rule, value, callback) => {
        if (!value) {
          callback(new Error('请选择结束时间'))
        }
        callback()
      }
      return {
        treeData: null,
        layout: {
          labelCol: { span: 5 },
          wrapperCol: { span: 16 }
        },
        proxyVisible: false,
        rowId: '',
        table: {
          columns: [],
          dataSource: [],
          loading: false
        },
        proxyInfo: {
          beginTime: undefined,
          endTime: undefined,
          agentId: '',
          agentName: ''
        },
        endOpen: false,
        rules: {
          beginTime: [{ validator: validateBeginTime, trigger: 'change' }],
          endTime: [{ validator: validateEndTime, trigger: 'change' }]
        }
      }
    },
    mounted () {
      this.init()
    },
    methods: {
      setRowClassName (record, index) {
        return this.rowId === index ? 'selected' : ''
      },
      onSelect (value, node, extra) {
        this.proxyInfo.agentName = node.title
      },
      listAgents () {
        this.table.columns = getColumns('proxySetting')
        orupService.getUserAgentList({}).then(resp => {
          this.table.dataSource = resp
        })
      },
      handleEdit (record) {
        this.proxyInfo = record
        this.proxyVisible = true
      },
      handleDelete (record) {
        orupService.deleteUserAgent({
          id: record.id
        }).then(resp => {
          this.listAgents()
        })
      },
      addAgentHandle () {
        this.proxyInfo = {}
        this.proxyVisible = true
      },
      handleOkEditProxy (proxyInfo) {
        this.$refs[proxyInfo].validate(valid => {
          if (valid) {
            orupService.saveUserAgent({}, this.proxyInfo).then(resp => {
              this.listAgents()
              this.handleCancelEdit('proxyInfo')
            })
          } else {
            console.log('error submit!!')
            return false
          }
        })
      },
      handleCancelEdit (proxyInfo) {
        this.$refs[proxyInfo].resetFields()
        this.proxyVisible = false
      },
      disabledBeginTime (beginTime) {
        const endTime = this.proxyInfo.endTime
        if (!beginTime || !endTime) {
          return false
        }
        return beginTime.valueOf() > endTime.valueOf()
      },
      disabledEndTime (endTime) {
        const beginTime = this.proxyInfo.beginTime
        if (!endTime || !beginTime) {
          return false
        }
        return beginTime.valueOf() >= endTime.valueOf()
      },
      handleBeginOpenChange (open) {
        if (!open) {
          this.endOpen = true
        }
      },
      handleEndOpenChange (open) {
        this.endOpen = open
      },
      loadOrgUser () {
        orupService.getOrgTreeWithUser().then((d) => {
          // 处理父节点不允许选择
          window.dp.treeEach(d, function (item) {
            if (item.treeNodeType == 'org') {
              item.disabled = true
            }
          })
          this.treeData = d
        })
      },
      refresh () {
        this.listAgents()
      },
      init () {
        this.listAgents()
        this.loadOrgUser()
      }
    }
  }
</script>

<style scoped lang="less">
  .proxy-setting{
    .icon-delete{
      color: red;
    }
    .cursor-pointer {
      cursor: pointer;
    }
  }
</style>
